package com.qing.config.scheduledTask;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qing.mapper.EmployeeMapper;
import com.qing.mapper.JobMapper;
import com.qing.mapper.SignInMapper;
import com.qing.pojo.Employee;
import com.qing.pojo.Job;
import com.qing.pojo.Leave;
import com.qing.pojo.Salary;
import com.qing.service.LeaveService;
import com.qing.service.SalaryService;
import com.qing.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author qinghua
 * @date 2022/6/19 22:03
 */
@Slf4j
@Service
public class ScheduledService {

    @Autowired
    private DateUtil dateUtil;

    @Autowired
    private SignInMapper signInMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private JobMapper jobMapper;

    @Autowired
    private SalaryService salaryService;

    @Autowired
    private LeaveService leaveService;

    /**
     * 月底统计员工工资
     */
    @Scheduled(cron = "0 0 23 28-31 * ?")
    public void checkEmployeeWorkDayNum() {
        final Calendar c = Calendar.getInstance();
        if (c.get(Calendar.DATE) == c.getActualMaximum(Calendar.DATE)) {
            // 是最后一天
            // 获取职位的全勤奖金 和 缺勤扣除金额 的Map集合
            Map<Integer, Integer> awardMap_temp = new HashMap<>();
            Map<Integer, Integer> deductionMap_temp = new HashMap<>();
            for (Job job : jobMapper.selectList(new QueryWrapper<Job>().select("id", "deduction", "award"))) {
                awardMap_temp.put(job.getId(), job.getAward());
                deductionMap_temp.put(job.getId(), job.getDeduction());
            }

            // 将jobId转成employeeId
            Map<Integer, Integer> deductionMap = new HashMap<>();
            Map<Integer, Integer> awardMap = new HashMap<>();
            Map<Integer, Integer> salaryMap = new HashMap<>();
            for (Employee employee : employeeMapper.selectList(new QueryWrapper<Employee>().select("id", "job_id", "base_salary"))) {
                deductionMap.put(employee.getId(), deductionMap_temp.get(employee.getJobId()));
                awardMap.put(employee.getId(), awardMap_temp.get(employee.getJobId()));
                salaryMap.put(employee.getId(), employee.getBaseSalary());
            }

            List<Salary> salaryList = new ArrayList<>();
            int workDay = dateUtil.getWorkDay(new SimpleDateFormat("yyyy-MM").format(new Date()));
            List<Map<String, Object>> allEmployeeWorkDayNum = signInMapper.getAllEmployeeWorkDayNum();
            // 如果某员工本月没有签到记录也就没有工资
            for (Map<String, Object> map : allEmployeeWorkDayNum) {
                Salary salary = new Salary();
                salary.setYearMouth(new SimpleDateFormat("yyyy-MM").format(new Date()));
                salary.setEmployeeId((Integer) map.get("employeeId"));
                if (Integer.parseInt(String.valueOf(map.get("count"))) < workDay) {
                    salary.setMonthCheck(workDay - Integer.parseInt(String.valueOf(map.get("count"))));
                    salary.setAward(0);
                    salary.setDeduction(deductionMap.get((Integer) map.get("employeeId")) * (workDay - Integer.parseInt(String.valueOf(map.get("count")))));
                } else {
                    salary.setMonthCheck(0);
                    salary.setAward(awardMap.get((Integer) map.get("employeeId")));
                    salary.setDeduction(0);
                }
                salary.setTotalSalary(salaryMap.get((Integer) map.get("employeeId")) + salary.getAward() - salary.getDeduction());
                salaryList.add(salary);
            }
            boolean b = salaryService.saveBatch(salaryList);
            if (b) {
                log.info("====================员工本月工资统计完成===================");
            } else {
                log.error("====================员工本月工资统计出错===================");
            }
        }
    }

    /**
     * 每天统计过期的请假（当天未审批的请假设为过期）
     */
    @Scheduled(cron = "0 59 23 * * ?")
    public void deleteExpiredLeaves() {
        List<Leave> leaves = leaveService.queryToday();
        if (leaves.size() > 0) {
            for (Leave leave : leaves) {
                if ("未审批".equals(leave.getResult())) {
                    leave.setResult("已过期");
                    System.out.println(leave);
                }
            }
        }
        boolean b = leaveService.updateBatchById(leaves);
        if (b) {
            log.info("====================过期请假修改完成===================");
        }else {
            log.info("====================过期请假修改失败===================");
        }
    }

}
